﻿using System;
using nRoute.Components.Routing;
using nRoute.Components;
using nRoute.Utilities;

namespace nRoute.Navigation.Mapping
{
    public class NavigationFileHandler : IRouteHandler
    {
        private const string FILEPATH_KEY = "filePath";

        private readonly Uri _resourceUri;

        internal NavigationFileHandler() { }
        
        public NavigationFileHandler(Uri resourceUri)
        {
            Guard.ArgumentNotNull(resourceUri, "resourceUri");
            _resourceUri = resourceUri;
        }

        IObservable<IUrlResponse> IRouteHandler.GetResponse(IRoutingContext context)
        {
            // note the content is the uri
            var _observer = new LazyRelayObservable<IUrlResponse>((s) =>
            {
                if (_resourceUri != null)
                {
                    s.OnNext(new UrlResponse(context.Request, ResponseStatus.Success, _resourceUri, context.ParsedParameters));
                }
                else if (context.ParsedParameters.ContainsKey(FILEPATH_KEY))
                {
                    var _filePathUri = new Uri(Convert.ToString(context.ParsedParameters[FILEPATH_KEY]), UriKind.Relative);
                    s.OnNext(new UrlResponse(context.Request, ResponseStatus.Success, _filePathUri, context.ParsedParameters));
                }
                else
                {
                    s.OnNext(new UrlResponse(context.Request, ResponseStatus.UrlNotFound, null));
                }
                s.OnCompleted();
            });
            return _observer;

        }
    }
}
